// user_announcement.js

import express from 'express';
const router = express.Router();
import { createConnectionPool } from '../../mysql/index.js';

const connection = await createConnectionPool();

router.get('/payment_record/get', async (req, res) => {
    try {
        // 执行查询
        const query = 'SELECT businessUser_id, businessUser_accountNumber, money, order_state, time, id,order_number FROM recharge_record';
        const result = await connection.query(query);
        // 将结果发送给客户端
        res.status(200).send({ code: 200, message: '获取数据成功', data: result[0] })
    } catch (error) {
        console.error('Error fetching payment records:', error);
        res.status(500).json({ error: 'Failed to fetch payment records' });
    }
})

// 生成订单号的函数

router.post('/payment_record/add', async (req, res) => {
    console.log("req.body", req.body);
    if (!req.body.businessUser_id || !req.body.businessUser_accountNumber || !req.body.money || !req.body.order_state) {
        return res.status(400).json({ error: 'businessUser_id, businessUser_accountNumber, money, and order_state are required parameters' });
    }

    const { businessUser_id, businessUser_accountNumber, money, order_state } = req.body;

    // 生成订单号
    const order_number = generateOrderNumber();
    try {

        const sql = `INSERT INTO recharge_record (businessUser_id, businessUser_accountNumber, money, order_number, order_state, time) 
                VALUES (?, ?, ?, ?, ?, ?)`;

        // 执行 SQL 查询
        await connection.query(sql, [businessUser_id, businessUser_accountNumber, money, order_number, order_state, new Date()]);

        console.log('Payment record added successfully');
        res.status(200).json({ message: 'Payment record added successfully' });
    } catch (error) {
        console.error('Error executing query: ' + error.stack);
        res.status(500).json({ error: 'An error occurred while adding payment record' });
    }
})

function generateOrderNumber() {
    const randomNumber = Math.floor(Math.random() * 10000000000000000000);
    return String(randomNumber).padStart(20, '0');
}


router.delete('/payment_record/delete', async (req, res) => {
    const { id } = req.body;

    try {
        // 检查参数是否提供
        if (!id) {
            return res.status(400).json({ error: 'id is required' });
        }
        // 构造 SQL 查询
        const sql = 'DELETE FROM recharge_record WHERE id = ?';
        // 执行 SQL 查询
        await connection.query(sql, [id]);

        console.log('Record with businessUser_id ' + id + ' deleted successfully');
        res.status(200).json({ message: 'Record deleted successfully' });
    } catch (error) {
        console.error('Error deleting record:', error);
        res.status(500).json({ error: 'An error occurred while deleting record' });
    }
});


export default router;
